package com.study.controller;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.study.config.TestJob;
import com.study.config.TestJob1;
import com.study.entity.Job;
import com.study.utils.QuartzUtil;

@RestController
public class TestQuartzController {

	@Autowired
	private Scheduler scheduler;
	
	@Autowired
	private QuartzUtil quartzUtil;
	
	@GetMapping("/test")
	public String test() throws Exception {
		 // 通过JobBuilder构建JobDetail实例，JobDetail规定只能是实现Job接口的实例
        // JobDetail 是具体Job实例
        JobDetail jobDetail = JobBuilder.newJob(TestJob.class).withIdentity("job1", "group1").build();
        
        // 基于表达式构建触发器
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0/5 * * * * ?");
        // CronTrigger表达式触发器 继承于Trigger
        // TriggerBuilder 用于构建触发器实例
        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("job1", "group1")
                .withSchedule(cronScheduleBuilder).build();
        scheduler.scheduleJob(jobDetail, cronTrigger);
        
        scheduler.start();
		return "success";
	}
	
	/**
	 * 加人任务并执行
	 * @return
	 */
	@GetMapping("/testJoin")
	public String testJoin() {
		System.out.println("测试加人任务并执行");
		Job job = new Job();
		job.setName("job1");
		job.setGroup("group1");
		job.setCron("0/5 * * * * ?");
		job.setStatus(1);
		job.setDesc("测试加人任务并执行");
		
		try {
			boolean b = quartzUtil.joinJob(job, TestJob1.class);
			if(b) {
				return "success";
			}
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
		return "fail";
	}
	
	/**
	 * 暂停任务
	 * @return
	 */
	@GetMapping("/testPause")
	public String testPause() {
		boolean b = quartzUtil.pauseJob("job1", "group1");
		if(b) {
			return "success";
		}
		return "fail";
	}
	
	/**
	 * 立即执行一次任务
	 * @return
	 */
	@GetMapping("/testRunOne")
	public String testRunOne() {
		Job job = new Job();
		job.setName("job1");
		job.setGroup("group1");
		job.setCron("0/5 * * * * ?");
		job.setStatus(1);
		job.setDesc("测试加人任务并执行一次");
		boolean b = quartzUtil.runNow(job);
		if(b) {
			return "success";
		}
		return "fail";
	}
}
